export interface IVThrottlingBinding {
  arg: keyof HTMLElementEventMap | undefined;
  modifiers: {
    [key: number | string]: boolean;
  };
  value: (ev: Event) => any;
}

export const vThrottling = {
  type: "click" as keyof HTMLElementEventMap,
  // 在绑定元素的 attribute 前
  // 或事件监听器应用前调用
  created(el: HTMLElement, { modifiers, arg }: IVThrottlingBinding) {
    // 默认为click事件
    if (!arg) {
      vThrottling.type = "click";
    } else {
      vThrottling.type = arg!;
    }

    const params = Object.keys(modifiers);

    if (params.length === 0) {
      el.delay = 1000;
      return;
    }

    const delayIndex = params.findIndex((item) => Number(item) >= 0);
    // 有参数，但是没有时间间隔毫秒数
    if (delayIndex < 0) {
      el.delay = 1000;
      return;
    }

    el.delay = parseInt(params[delayIndex]);
  },

  mounted(el: HTMLElement, { value: handleEvent }: IVThrottlingBinding) {
    el.addEventListener(
      vThrottling.type,
      async (event: Event) => {
        const time = el.timer as number | null;

        if (!time) {
          await handleEvent(event);
          el.timer = Date.now();
          return;
        }

        const current = Date.now();
        if (current - time <= el.delay!) {
          return;
        }
        await handleEvent(event);
        el.timer = Date.now();
      },
      false
    );
  },
  // 绑定元素的父组件卸载后调用
  unmounted(el: HTMLElement, { value }: IVThrottlingBinding) {
    el.removeEventListener(vThrottling.type, value, false);
  },
};
